const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const path = require('path');
const compression = require('compression');
const authRoutes = require('./server/routes/auth');
const taskRoutes = require('./server/routes/tasks');

const app = express();

// 启用gzip压缩，降低压缩级别以减少CPU占用
app.use(compression({
  level: 1,
  threshold: 0
}));

// 中间件配置
app.use(cors());
app.use(express.json({ limit: '1mb' }));

// 处理favicon请求
app.get('/favicon.ico', (req, res) => {
  res.sendFile(path.join(__dirname, 'public', 'favicon.ico'));
});

// MongoDB连接配置
const mongoOptions = {
  useNewUrlParser: true,
  useUnifiedTopology: true,
  serverSelectionTimeoutMS: 10000,
  connectTimeoutMS: 10000,
  socketTimeoutMS: 45000,
  retryWrites: true,
  retryReads: true,
};

// 连接MongoDB
console.log('正在连接MongoDB...');
mongoose.connect('mongodb://127.0.0.1:27017/green_planet', mongoOptions)
  .then(() => {
    console.log('MongoDB连接成功！');
  })
  .catch((err) => {
    console.error('MongoDB连接失败:', err);
    console.log('继续启动服务器，但部分功能可能不可用...');
  });

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/tasks', taskRoutes);

// 静态文件服务优化
const staticOptions = {
  maxAge: '1h',
  etag: true,
  lastModified: true,
  setHeaders: (res, path) => {
    if (path.endsWith('.html')) {
      res.setHeader('Cache-Control', 'no-cache');
    } else {
      res.setHeader('Cache-Control', 'public, max-age=3600');
    }
  }
};

// 使用express.static中间件提供静态文件服务
app.use(express.static(path.join(__dirname, 'build'), staticOptions));
app.use(express.static(path.join(__dirname, 'public'), staticOptions));

// 检查build文件夹是否存在
const fs = require('fs');
if (!fs.existsSync(path.join(__dirname, 'build'))) {
  console.error('Error: build folder does not exist!');
  console.log('Please run npm run build to generate the build folder');
  process.exit(1);
}

// 所有其他请求返回React应用
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));
});

// 错误处理中间件优化
app.use((err, req, res, next) => {
  console.error('Server error:', err.stack);
  res.status(500).json({ 
    message: 'Server error, please try again later',
    error: process.env.NODE_ENV === 'development' ? err.message : undefined
  });
});

// 设置服务器超时
app.timeout = 30000; // 30秒超时

const PORT = process.env.PORT || 3000;
const server = app.listen(PORT, '0.0.0.0', () => {
  console.log(`Server running on port ${PORT}`);
  console.log(`Local access: http://localhost:${PORT}`);
  
  // 获取本机IP地址
  const { networkInterfaces } = require('os');
  const nets = networkInterfaces();
  let localIP = '';
  
  // 遍历网络接口获取IPv4地址
  Object.keys(nets).forEach((name) => {
    for (const net of nets[name]) {
      if (net.family === 'IPv4' && !net.internal) {
        localIP = net.address;
      }
    }
  });
  
  if (localIP) {
    console.log(`Network access: http://${localIP}:${PORT}`);
  }
});

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('SIGTERM signal received: closing HTTP server');
  server.close(() => {
    console.log('HTTP server closed');
    mongoose.connection.close(false, () => {
      console.log('MongoDB connection closed');
      process.exit(0);
    });
  });
}); 
